<template>
  <div class="content_box">
    <form class="condition_query">
      <span class="txt">设备来源</span>
      <el-select class="inline-input" size="medium" v-model="deviceSource" clearable placeholder="请选择">
        <el-option v-for="item in deviceSourceList" :key="item.value" :label="item.label" :value="item.label" />
      </el-select>

      <span class="txt">标段</span>
      <el-select class="inline-input" size="medium" v-model="bidSection" clearable placeholder="请选择">
        <el-option v-for="item in biaoduanList" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>

      <span class="txt">报审表编号</span>
      <el-input v-model="examinationNumber" size="medium" clearable style="width: 160px; margin-right: 22px;" placeholder="请输入" />

      <span class="txt">进场时间</span>
      <el-date-picker
        v-model="time"
        style="width: 270px"
        size="medium"
        type="daterange"
        value-format="yyyy-MM-dd"
        format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-button type="primary" size="medium" icon="el-icon-search" style="margin-left:40px" @click="queryListData">查询</el-button>
    </form>

    <div>
      <el-table
        :data="deviceList"
        :height="tableHeight"
        size="small"
        style="width: 100%;"
        v-loading="loading"
        :row-class-name="tableRowClassName">
        <el-table-column type="index" label="No" :index="indexMethod" fixed width="36"></el-table-column>
        <el-table-column prop="deviceCnName" label="设备名称" fixed width="140">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="deviceDetails(scope.row.id)">{{ scope.row.deviceCnName }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="mobilizationSerialNumber" label="进场编号" width="170"></el-table-column>
        <el-table-column prop="bidSection" label="标段" width="150"></el-table-column>
        <el-table-column prop="deviceTypeName" label="设备类型" width="150"></el-table-column>
        <el-table-column prop="model" label="规格型号" width="150"></el-table-column>
        <el-table-column prop="examinationNumber" label="报审表编号" width="150"></el-table-column>
        <el-table-column prop="deviceSource" label="设备来源" width="150"></el-table-column>
        <el-table-column label="进/退场" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.entryStatus == 1 ? "已进场" : "已退场" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="mobilization_time" label="进场时间" width="150"></el-table-column>
<!--        <el-table-column prop="username" label="推送人" width="150"></el-table-column>-->
<!--        <el-table-column prop="userTel" label="手机号码" width="150"></el-table-column>-->
<!--        <el-table-column prop="weizhi" label="位置信息" width="200"></el-table-column>-->
        <el-table-column prop="runningState" label="运行状态" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.runningState == 1 ? "在线" : "离线" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="yunxingsc" label="运行时长" width="150"></el-table-column>
<!--        <el-table-column prop="yunxinggl" label="运行公里" width="150"></el-table-column>-->
<!--        <el-table-column prop="ranyoufy" label="燃油费用(合计)" width="150"></el-table-column>-->
<!--        <el-table-column prop="yunyingfy" label="运营费用" width="150"></el-table-column>-->
        <el-table-column fixed="right" label="检定记录" width="70">
          <template slot-scope="scope">
            <div style="text-align: center">
              <el-button type="text" size="small" @click="showRecordTest(scope.row.id)">查看</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="维保记录" width="70">
          <template slot-scope="scope">
            <div style="text-align: center">
              <el-button type="text" size="small" @click="showRecordModelList(scope.row.id)">查看</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="140">
          <template slot-scope="scope" v-if="scope.row.entryStatus == 1">
            <el-button type="text" size="small" @click="modifDeviceInfo(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="delDeviceInfo(scope.row)">删除</el-button>
            <el-button type="text" size="small" @click="showRecordModel(scope.row)">退场</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :pageData="pageData" @pageNum="pageNumData" @pageSize="pageSizeData"></Pagination>

      <el-dialog title="设备退场" :visible.sync="dialogVisible" width="500px">
        <div class="info-modal">
          <span class="text">退场登记时间：</span>
          <el-date-picker
            style="width: 260px;"
            size="medium"
            v-model="form.exitTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            @change="changeExitTime">
          </el-date-picker>
        </div>
        <div class="info-modal">
          <span class="text">退场登记人：</span>
          <el-input style="width: 260px;" size="medium" placeholder="请输入" v-model.trim="form.exitRegisterPerson" />
        </div>
        <div class="info-modal">
          <span class="text">相关处理人：</span>
          <el-input style="width: 260px;" size="medium" placeholder="请输入" v-model.trim="form.exitHandler" />
        </div>
        <div class="info-modal">
          <span class="text">备注：</span>
          <el-input
            type="textarea"
            class="textarea"
            :rows="3"
            placeholder="请输入内容"
            maxlength="100"
            show-word-limit
            v-model="form.exitRemark">
          </el-input>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addWalkOff">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 维保记录 -->
      <ServiceRecordModel ref="ServiceRecordRef"></ServiceRecordModel>

      <!--  检定记录    -->
      <TestRecordModal ref="TestRecordRef"></TestRecordModal>
    </div>
  </div>
</template>

<script>
import Pagination from "../Pagination";
import TestRecordModal from "../../models/TestRecordModal";
import ServiceRecordModel from "../../models/ServiceRecordModel";
import HttpInterface from "../../../util/httpInterface";
import Constants from "../../../util/constants";
import { mapState } from "vuex";

export default {
	name: "DeviceListData",
  components: {
    Pagination, TestRecordModal, ServiceRecordModel
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      deviceList: [],
      tableHeight: 0,
      deviceSourceList: [
        { value: '1', label: '自有' },
        { value: '2', label: '租凭' },
      ],
      form: {
        exitRegisterPerson: "",
        exitTime: "",
        exitHandler: "",
        exitRemark: ""
      },
      time: [],
      bidSection: "",
      deviceSource: "",
      report: "",
      examinationNumber: "",
      pageData: {
        total: 0,
        pageNum: 1,
        pageSize: 20
      }
    };
	},

  computed: {
	  ...mapState(["biaoduanList"])
  },

	created() {
    this.getTableHeight();
  },

  mounted() {
    let _this = this;
    let resizeFlag = null;
    window.onresize = () => {
      if (resizeFlag) {
        clearTimeout(resizeFlag);
      }
      resizeFlag = setTimeout(() => {
        _this.getTableHeight();
        resizeFlag = null;
      }, 120);
    };
  },

  beforeDestroy() {
    window.onresize = null;
  },

  methods: {
    getTableHeight() {
      let tableH = 220;
      let tableHeightDetil = window.innerHeight - tableH;
      if (tableHeightDetil <= 300) {
        this.tableHeight = 300;
      } else {
        this.tableHeight = window.innerHeight - tableH;
      }
    },

    indexMethod (index) {
      return index + 1;
    },

    pageNumData (page) {
      this.pageData.pageNum = Number(page);
      this.queryListData();
    },

    pageSizeData (page) {
      this.pageData.pageSize = Number(page);
      this.queryListData();
    },

    tableRowClassName({row}) {
      if (row.entryStatus != 1) {
        return 'warning-row';
      }
      return '';
    },

    // 查询数据
    queryListData () {
      this.loading = true;
      let _this = this;
      let searchMap = {
        page: this.pageData.pageNum,
        size: this.pageData.pageSize,
        report: this.report,
        deviceSource: this.deviceSource,
        bidSection: this.bidSection,
        examinationNumber: this.examinationNumber
      }
      if (this.time != null && this.time.length != 0) {
        searchMap.startTime = this.time[0] + " 00:00:00";
        searchMap.endTime = this.time[1] + " 23:59:59";
      } else {
        searchMap.startTime = "";
        searchMap.endTime = "";
      }
      HttpInterface.requestPost(this, HttpInterface.URL_DEVICE_FIND_PAGE, searchMap, function (res) {
        let data = res.data;
        if (data.success) {
          let rows = data.other.rows;
          rows.forEach(item => {
            item.deviceTypeName = Constants.DEVICE_TYPE_LIST[item.deviceType];
            item.guaStatus = item.guaranteeStatus == 0 ? "关闭" : "打开";
            item.youhao = item.company == "1" ? item.consumption + " - L/小时" : item.consumption + " - L/100公里";
            if (item.mobilizationTime) {
              item.mobilization_time = item.mobilizationTime.slice(0, 10);
            }
            if (item.endTime && item.startTime) {
              item.starttime = item.startTime.slice(0, 10);
              item.endtime = item.endTime.slice(0, 10);
              item.timeSlot = item.starttime.replace(/-/g, ".") + " - " + item.endtime.replace(/-/g, ".");
            }
          })
          rows.sort(function (a, b) {
            return b.entryStatus - a.entryStatus;
          })
          _this.loading = false;
          _this.deviceList = rows;
          _this.pageData.total = data.other.total;
        } else {
          _this.loading = false;
          _this.errorMessage("获取数据失败！");
        }
      }, function (err) {
        _this.loading = false;
        _this.errorMessage("获取数据失败！");
      }, false)
    },

    // 设备详情
    deviceDetails(id) {
      this.$nextTick(() => {
        this.$emit('details', id);
      })
    },

    // 修改
    modifDeviceInfo (row) {
      this.$emit("modifDevice", row.id);
    },

    // 删除
    delDeviceInfo(row) {
      let _this = this;
      this.$confirm('此操作将永久删除这条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = {
          id: row.id
        }
        HttpInterface.requestGet(this, HttpInterface.URL_DELETE_MECHANICAL_DEVICE, params, function (res) {
          let data = res.data;
          if (data.success) {
            _this.successMessage("删除成功！");
            _this.queryListData();
          } else {
            _this.errorMessage("删除失败！");
          }
        }, null)
      }).catch(() => {});
    },

    // 记录
    showRecordModel (row) {
      this.dialogVisible = true;
      this.id = row.id;
      this.form = {
        exitRegisterPerson: "",
        exitTime: "",
        exitHandler: "",
        entryStatus: 0,  // 进出场状态 1进场 0退场
        exitRemark: ""
      };
      let _this = this;
      let params = {
        id: row.id
      };
      HttpInterface.requestGet(this, HttpInterface.URL_GET_BY_MECHANICAL_DEVICEID, params, function (res) {
        let data = res.data;
        if (data.success) {
          _this.acceptanceCheck = data.other.acceptanceCheck;
          _this.mechanicalDevice = data.other.mechanicalDevice;
        }
      }, null)
    },

    // 选择 退场登记时间
    changeExitTime() {
      if (!this.mechanicalDevice.mobilizationTime) return this.errorMessage("当前数据没有进场时间！");
      let mobilizationTime = this.mechanicalDevice.mobilizationTime.slice(0, 10);
      let time = +new Date(mobilizationTime);  // 进场时间
      let date = +new Date(this.form.exitTime);  // 退场时间
      if (date < time) {
        this.errorMessage("退场时间不能小于进场时间！");
        return false;
      }
      return true;
    },

    // 添加退场记录
    addWalkOff() {
      if (!this.changeExitTime()) {
        return false;
      }
      let _this = this;
      let params = {
        acceptanceCheck: this.acceptanceCheck,
        mechanicalDevice: this.mechanicalDevice
      };
      params.mechanicalDevice.exitRegisterPerson = this.form.exitRegisterPerson;
      params.mechanicalDevice.exitTime = this.form.exitTime;
      params.mechanicalDevice.exitHandler = this.form.exitHandler;
      params.mechanicalDevice.entryStatus = this.form.entryStatus;
      params.mechanicalDevice.exitRemark = this.form.exitRemark;
      params.acceptanceCheck[0].designDocument = [];
      params.acceptanceCheck[0].certificates = [];
      params.acceptanceCheck[0].installationUnits = [];
      params.acceptanceCheck[0].testingUnits = [];
      params.acceptanceCheck[0].instruction = [];
      params.acceptanceCheck[0].maintenanceInstruction = [];
      params.acceptanceCheck[0].inspectionCertificates = [];
      params.acceptanceCheck[0].certificateRegistrations = [];
      params.acceptanceCheck[0].licences = [];
      params.acceptanceCheck[0].leaseAgreements = [];
      params.acceptanceCheck[0].purchaseContracts = [];
      params.acceptanceCheck[0].reports = [];
      HttpInterface.requestPost(this, HttpInterface.URL_UPDATE_MECHANICAL_DEVICE, params, function (res) {
        let data = res.data;
        if (data.success) {
          _this.dialogVisible = false;
          _this.successMessage('添加退场记录成功！');
          _this.queryListData();
        } else {
          _this.dialogVisible = true;
          _this.errorMessage('操作失败！');
        }
      }, null, false)
    },

    // 检定记录
    showRecordTest(checkId){
      this.$refs.TestRecordRef.modalShow(checkId)
    },

    // 维保记录
    showRecordModelList (matainId) {
      this.$refs.ServiceRecordRef.show(matainId);
    },
  }
};
</script>

<style scoped lang="scss">
  .condition_query{
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }

  .txt{
    margin-right: 10px;
    font-size: 14px;
  }

  .inline-input{
    width: 120px;
    margin-right: 22px;
  }

  .el-table--small >>> td {
    padding: 4px 0;
  }

  .info-modal{
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 20px 0;

    .text{
      font-size: 14px;
      margin-right: 10px;
      width: 100px;
      display: inline-block;
      text-align: right;
    }

    .textarea{
      width: 260px;
    }
  }

  .el-dialog__wrapper >>> .el-dialog .el-dialog__body {
    padding: 6px 20px;
  }

  .el-textarea >>> .el-textarea__inner{
    border-radius: 1px;
  }

  .el-table >>> .warning-row {
    background: #fdf5e6;
  }
</style>
